package com.google.android.daca;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class CreatePollActivity extends Activity {

	/**
	 * Login screen to choose a new name to be used for polls or edit an
	 * existing previously saved one and optionally a Doodle poll ID (if the
	 * user started the DACA app himself and not through a URL). Then forward to
	 * the next activity.
	 * 
	 * @author istoychev
	 */

	private static final String CLASS_TAG = CreatePollActivity.class
			.getSimpleName();
	private Button nextBtn;
	private EditText initiatorName;
	private EditText pollTittle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_poll);

		initiatorName = (EditText) findViewById(R.id.daca_poll_initiator_name_label);
		pollTittle = (EditText) findViewById(R.id.daca_poll_tittle_label);

		nextBtn = (Button) findViewById(R.id.btn_next);
		nextBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!validate())
					return;
				Intent intent = new Intent(CreatePollActivity.this,
						OptionsActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("Initiator", initiatorName.getText()
						.toString());
				bundle.putString("Title", pollTittle.getText().toString());
				bundle.putString("Description", "");
				intent.putExtras(bundle);
				startActivityForResult(intent, 0);
			}
		});
	}

	/**
	 * Validate form fields for creating poll
	 * 
	 */
	private boolean validate() {
		boolean valid = true;

		StringBuilder validationText = new StringBuilder();
		if (initiatorName.getText() == null
				|| initiatorName.getText().toString().trim().length() == 0) {
			validationText.append(getResources().getString(
					R.string.initiator_name_not_supplied_message));
			valid = false;
		}
		if (pollTittle.getText() == null
				|| pollTittle.getText().toString().trim().length() == 0) {
			validationText.append(" "
					+ getResources().getString(
							R.string.poll_title_not_supplied_message));
			valid = false;
		}
		if (!valid) {
			Log.v(CLASS_TAG, "User input not valid.");
			new AlertDialog.Builder(this).setTitle(
					getResources().getString(R.string.alert_label)).setMessage(
					validationText.toString()).setPositiveButton("Continue",
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int arg1) {
							// in this case, don't need to do anything other
							// than close alert
						}
					}).show();
		}

		return valid;
	}

}
